package com.gai.shop.dao.impl;

import com.gai.shop.dao.ItemDao;
import com.gai.shop.entity.Item;
import com.gai.shop.entity.Product;
import com.gai.shop.util.DataBaseUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ItemDaoImpl implements ItemDao {
    private final QueryRunner QR = new QueryRunner();

    /**
     * 批量新增的操作
     * @param items
     */
    @Override
    public void insertIntoItems(List<Item> items) throws Exception {
        Object[][] param = new Object[items.size()][];
        //循环遍历
        for (int i = 0; i < items.size(); i++) {
            Item item = items.get(i);
            param[i] = new Object[]{item.getOid(),item.getPid(),item.getIcount(),item.getInum()};
        }
        //批量新增
        QR.batch(DataBaseUtil.getConnection(),
                "INSERT INTO item VALUES (DEFAULT,?,?,?,?);",
                param);
    }

    /**
     * 使用oid查询item集合
     * @param oid
     * @return
     * @throws Exception
     */
    @Override
    public List<Item> getItemByOid(String oid) throws Exception {
        String sql = "SELECT i.iid,i.oid,i.icount,i.inum,p.pid,p.pname,p.ptime,p.pimage,p.pprice,p.pstate,p.pinfo " +
                "FROM  item i,product p WHERE i.pid = p.pid AND i.oid = ?";
        List<Map<String, Object>> mapList = QR.query(DataBaseUtil.getConnection(),
                sql,
                new MapListHandler(),
                oid);
        if (mapList == null) {
            return null;
        }
        List<Item> itemList = new ArrayList<>();
        for (Map<String, Object> query : mapList) {
            //声明需要封装的实体类
            Item item = new Item();
            Product product = new Product();
            BeanUtils.populate(item,query);
            BeanUtils.populate(product,query);
            item.setPro(product);
            itemList.add(item);
        }
        return itemList;
    }
}
